/*
 * Copyright (C) 2010 Imavis Srl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.imavis.video.parse.impl;

import java.nio.ByteBuffer;

/**
 * A bit buffer.
 * This class allows the caller to get single bits or arbitrary length integers
 * from an underlying {@code ByteBuffer}.
 *
 * @author Aldo Brucale
 * @author Andrea Gualano
 */
public final class BitBuffer {
    private final ByteBuffer bb;
    private int available;
    private int buffer;

    public BitBuffer(final ByteBuffer bb) {
        this.bb = bb;
        this.available = 0;
        this.buffer = 0;
    }

    public boolean getBit() {
        return getBits(1) != 0;
    }

    public int getBits(final int nBits) {
        if (nBits < 0 || nBits > 32) {
            throw new IllegalArgumentException();
        }
        if (nBits == 0) {
            return 0;
        }

        long bits = buffer;
        int collected = available;
        while (collected < nBits) {
            bits = (bits << 8) | (bb.get() & 0xFF);
            collected += 8;
        }

        available = collected - nBits;
        assert available < 8;
        final int result = (int) (bits >> available);
        buffer = (int) (bits & ((1 << available) - 1));
        return result;
    }
}
